﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;
using DGSFramework;
using System.Web.Security;
using System.Text.RegularExpressions;
using System.Web.UI.HtmlControls;
using System.Web.Services;

namespace Framework.WebmasterTool.Products
{
    public partial class Default : System.Web.UI.Page
    {
        DGSFrameworkEntities entity = new DGSFrameworkEntities();

        public string GridViewSortExpression
        {
            get { return ViewState["GridViewSortExpression"] == null ? "AddedDate" : ViewState["GridViewSortExpression"] as string; }
            set { ViewState["GridViewSortExpression"] = value; }
        }

        public SortDirection GridViewSortOrder
        {
            get { return ViewState["GridViewSortOrder"] == null ? SortDirection.Descending : (SortDirection)ViewState["GridViewSortOrder"]; }
            set { ViewState["GridViewSortOrder"] = value; }
        }

        protected void Page_Load(object sender, EventArgs e)
        {
            if (!IsPostBack)
            {
                CheckPermission();
                LoadCateDDL();
                LoadProducts();
            }
        }

        public void CheckPermission()
        {
            MembershipUser someUser = Membership.GetUser();
            if (someUser == null)
            {
                Response.Redirect(Globals.ApplicationPath + "LoginAdmin/Default.aspx");
            }
            bool flag = false;
            var user = entity.aspnet_Users.Where(us => us.UserName == someUser.UserName).FirstOrDefault();
            user.aspnet_Roles.Load();
            var rolesForUser = user.aspnet_Roles.ToList();
            foreach (var item in rolesForUser)
            {
                var permission = entity.udv_Permissions.Where(ps => ps.RoleId == item.RoleId).FirstOrDefault();
                if (permission.Product.Value == true)
                {
                    flag = true;
                }
            }
            if (flag == false)
            {
                lblPermissionMessage.Visible = true;
                Panel1.Visible = false;
            }
        }

        public void LoadCateDDL()
        {
            string levels = "|---";
            string spaces = "&nbsp;";
            List<udv_Categories> allCate = entity.udv_Categories.ToList();
            List<udv_Categories> cateBannerParent = allCate.Where(ca => ca.ParentID == ConfigPaths.Category_Product_ID).ToList();
            foreach (var item in cateBannerParent)
            {
                ddlCategories.Items.Add(new ListItem(item.Title, item.CateID.ToString()));
                LoadSubCateDDL(ref allCate, item.CateID, ref spaces, levels);
            }
        }

        public void LoadSubCateDDL(ref List<udv_Categories> allCate, int cateParentID, ref string spaces, string levels)
        {
            List<udv_Categories> subCateBanner = allCate.Where(ca => ca.ParentID == cateParentID).ToList();
            foreach (var item in subCateBanner)
            {
                ddlCategories.Items.Add(new ListItem(HttpUtility.HtmlDecode(spaces) + levels + item.Title, item.CateID.ToString()));
                if (entity.udv_Categories.Where(ca => ca.ParentID == item.CateID).ToList().Count > 0)
                {
                    spaces += "&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;";
                    LoadSubCateDDL(ref allCate, item.CateID, ref spaces, levels);
                }
            }
            if (spaces.Length > 6)
                spaces = spaces.Substring(0, spaces.Length - 36);
        }

        public void LoadProducts()
        {
            var products = entity.udv_Products.Include("udv_Categories").Select(pd => new { pd.ProductID, pd.ImageUrl, pd.Title, CateID = pd.udv_Categories.CateID, CateTitle = pd.udv_Categories.Title, pd.AddedDate, pd.IsActive, pd.DisplayOrder, pd.SalePrice }).ToList();
            if (GridViewSortOrder.Equals(SortDirection.Ascending))
                products = products.OrderBy(a => a.GetType().GetProperty(GridViewSortExpression).GetValue(a, null)).ToList();
            else
                products = products.OrderByDescending(a => a.GetType().GetProperty(GridViewSortExpression).GetValue(a, null)).ToList();
            grvProducts.DataSource = products;
            grvProducts.DataBind();
        }

        protected void grvProducts_Sorting(object sender, GridViewSortEventArgs e)
        {
            //Check if the same column is sorted to switch Sort Order  
            if (GridViewSortExpression.Equals(e.SortExpression))
                GridViewSortOrder = GridViewSortOrder.Equals(SortDirection.Ascending) ? SortDirection.Descending : SortDirection.Ascending;
            else
                GridViewSortOrder = SortDirection.Ascending;
            //save Sort Expression and Sort Order
            GridViewSortExpression = e.SortExpression;
            if (grvProducts.ToolTip == "all")
                LoadProducts();
            else
            {
                SearchProducts();
            }
        }

        protected void grvProducts_DataBinding(object sender, EventArgs e)
        {
            string srcImageASC = Globals.ApplicationPath + "WebmasterTool/Images/ASC.gif";
            string srcImageDESC = Globals.ApplicationPath + "WebmasterTool/Images/DESC.gif";
            foreach (DataControlField column in grvProducts.Columns)
            {
                //Remove Previous Sort Image  
                column.HeaderText = Regex.Replace(column.HeaderText, "<[^>]*>", "", RegexOptions.IgnoreCase);
                if (column.SortExpression.Equals(GridViewSortExpression))
                {
                    //set new sort image  
                    string strSortImageURL = GridViewSortOrder == SortDirection.Descending ?
                                            "<img border='0' style='background-color:White;vertical-align:middle;' src='" + srcImageDESC + "' />" :
                                            "<img border='0' style='background-color:White;vertical-align:middle;' src='" + srcImageASC + "' />";
                    column.HeaderText = String.Format("{0}{1}", column.HeaderText, strSortImageURL);
                }
            }
        }

        protected void grvProducts_PageIndexChanging(object sender, GridViewPageEventArgs e)
        {
            grvProducts.PageIndex = e.NewPageIndex;
            if (grvProducts.ToolTip == "all")
                LoadProducts();
            else
            {
                SearchProducts();
            }
        }

        public void SearchProducts()
        {
            var products = entity.udv_Products.Include("udv_Categories").Select(pd => new { pd.ProductID, pd.ImageUrl, pd.Title, CateID = pd.udv_Categories.CateID, CateTitle = pd.udv_Categories.Title, pd.AddedDate, pd.IsActive, pd.DisplayOrder, pd.SalePrice }).ToList();
            var searchProducts = entity.udv_Products.Include("udv_Categories").Where(pd => pd.ProductID == -1).Select(pd => new { pd.ProductID, pd.ImageUrl, pd.Title, CateID = pd.udv_Categories.CateID, CateTitle = pd.udv_Categories.Title, pd.AddedDate, pd.IsActive, pd.DisplayOrder, pd.SalePrice }).ToList();
            if (txtKeyword.Text.Trim() == "" && ddlCategories.SelectedValue != "0")
            {
                int cateID = int.Parse(ddlCategories.SelectedValue);
                List<udv_Categories> allCate = entity.udv_Categories.ToList();
                List<udv_Categories> searchCate = Globals.LoopGetCategories(ref allCate, cateID);
                searchCate.Add(allCate.Where(ca => ca.CateID == cateID).FirstOrDefault());
                foreach (var item in searchCate)
                {
                    searchProducts.AddRange(products.Where(ar => ar.CateID == item.CateID).ToList());
                }
            }
            else if (txtKeyword.Text.Trim() != "" && ddlCategories.SelectedValue == "0")
            {
                string keywords = Globals.RemoveSign4VietnameseString(txtKeyword.Text.Trim().ToLower());
                searchProducts = products.Where(pd => Globals.RemoveSign4VietnameseString(pd.Title.ToLower()).Contains(keywords) || pd.AddedDate.ToString("dd/MM/yyyy").Contains(keywords)).ToList();
            }
            else if (txtKeyword.Text.Trim() != "" && ddlCategories.SelectedValue != "0")
            {
                int cateID = int.Parse(ddlCategories.SelectedValue);
                string keywords = Globals.RemoveSign4VietnameseString(txtKeyword.Text.Trim());
                List<udv_Categories> allCate = entity.udv_Categories.ToList();
                List<udv_Categories> searchCate = Globals.LoopGetCategories(ref allCate, cateID);
                searchCate.Add(allCate.Where(ca => ca.CateID == cateID).FirstOrDefault());
                foreach (var item in searchCate)
                {
                    searchProducts.AddRange(products.Where(pd => (Globals.RemoveSign4VietnameseString(pd.Title.ToLower()).Contains(keywords) || pd.AddedDate.ToString("dd/MM/yyyy").Contains(keywords)) && pd.CateID == item.CateID).ToList());
                }
            }
            else
                searchProducts = products;
            if (GridViewSortOrder.Equals(SortDirection.Ascending))
                searchProducts = searchProducts.OrderBy(a => a.GetType().GetProperty(GridViewSortExpression).GetValue(a, null)).ToList();
            else
                searchProducts = searchProducts.OrderByDescending(a => a.GetType().GetProperty(GridViewSortExpression).GetValue(a, null)).ToList();
            grvProducts.DataSource = searchProducts;
            grvProducts.DataBind();
        }

        protected void btnSearch_Click(object sender, EventArgs e)
        {
            grvProducts.PageIndex = 0;
            grvProducts.ToolTip = "search";
            SearchProducts();
        }

        protected void btnNew_Click(object sender, EventArgs e)
        {
            Response.Redirect("ProductAdd.aspx");
        }

        protected void btnDelete_Click(object sender, EventArgs e)
        {
            foreach (GridViewRow row in grvProducts.Rows)
            {
                bool isChecked = ((HtmlInputCheckBox)row.FindControl("chkSelect")).Checked;
                if (isChecked)
                {
                    int productID = int.Parse(((HtmlInputCheckBox)row.FindControl("chkSelect")).Attributes["title"].Trim());
                    udv_Products productDelete = entity.udv_Products.Where(pr => pr.ProductID == productID).FirstOrDefault();
                    if (productDelete != null)
                    {
                        List<udv_ProductImages> listProductImage = entity.udv_ProductImages.Where(ip => ip.udv_Products.ProductID == productDelete.ProductID).ToList();
                        foreach (var item in listProductImage)
                        {
                            Globals.DelelteFile(Server.MapPath(ConfigPaths.Path_ImageProduct_Folder_MapPath + item.ImageUrl));
                        }
                        Globals.DelelteFile(Server.MapPath(ConfigPaths.Path_ImageProduct_Folder_MapPath + productDelete.ImageUrl));
                        //output cache
                        string key = "/ProductDetails.aspx?ProductID=" + productDelete.ProductID.ToString();
                        Cache.Remove(key);
                        string urlRewriteProductOld = Globals.CreateUrlRewriteProduct(ref entity, productDelete.ProductID, true) + DGSFramework.Globals.GetUrlRewriteExtension();
                        Globals.DeleteROR("~/ror.xml", urlRewriteProductOld);
                        Globals.DeleteSiteMap("~/sitemap.xml", urlRewriteProductOld);
                        Globals.DeleteUrlList("~/urllist.txt", urlRewriteProductOld);

                        //create db log
                        productDelete.udv_CategoriesReference.Load();
                        CreateDBLog(productDelete.ProductID, productDelete.udv_Categories.CateID, TypeAction.Delete, "Xoá bài viết sản phẩm: " + productDelete.Title, productDelete.Summary, productDelete.Description, productDelete.ReleaseDate != null ? string.Format("{0:dd/MM/yyyy} HH:mm:ss", productDelete.ReleaseDate) : "", productDelete.ReleaseDate != null ? string.Format("{0:dd/MM/yyyy} HH:mm:ss", productDelete.ReleaseDate) : "",
                            productDelete.IsActive.Value.ToString(), productDelete.StatusID.Value.ToString(), productDelete.MetaDescription, productDelete.MetaKeywords);

                        entity.DeleteObject(productDelete);
                        entity.SaveChanges();
                    }
                }
            }
            //data cache
            Cache.Remove("Product");
            //output cache
            HttpResponse.RemoveOutputCacheItem("/Default.aspx");
            HttpResponse.RemoveOutputCacheItem("/Products.aspx");
            if (grvProducts.ToolTip == "all")
                LoadProducts();
            else
            {
                SearchProducts();
            }
        }

        [WebMethod]
        public static void UpdateIsActive(string ProductID, string IsActive)
        {
            DGSFrameworkEntities entity = new DGSFrameworkEntities();
            int productID = int.Parse(ProductID);
            bool isActive = IsActive == "1" ? true : false;

            udv_Products product = entity.udv_Products.Where(pr => pr.ProductID == productID).FirstOrDefault();
            if (product != null)
            {
                product.IsActive = isActive;
                entity.SaveChanges();
            }
        }

        [WebMethod]
        public static void UpdateDisplayOrder(string LstProductID, string LstDisplayOrder)
        {
            DGSFrameworkEntities entity = new DGSFrameworkEntities();
            var lstProductID = LstProductID.Split(',');
            var lstDisplayOrder = LstDisplayOrder.Split(',');

            if (lstProductID.Count() == lstDisplayOrder.Count())
            {
                for (int i = 0; i < lstProductID.Count(); i++)
                {
                    int productID = int.Parse(lstProductID[i]);
                    int displayOrder = int.Parse(lstDisplayOrder[i]);

                    udv_Products product = entity.udv_Products.Where(pr => pr.ProductID == productID).FirstOrDefault();
                    if (product != null)
                    {
                        product.DisplayOrder = displayOrder;
                        entity.SaveChanges();
                    }
                }
            }
        }

        public void CreateDBLog(int? postID, int? postCateID, TypeAction typeAction, string title, string _abstract, string description,
        string releaseDate, string expireDate, string isApproved, string statusID, string metaDescription, string metaKeywords)
        {
            udv_Log log = new udv_Log();
            log.PostID = postID;
            log.PostCateID = postCateID;
            log.TypeAction = (int)typeAction;
            log.Title = title;
            log.Abstract = _abstract;
            log.Description = description;
            log.ReleaseDate = releaseDate;
            log.ExpireDate = expireDate;
            log.IsApproved = isApproved;
            log.StatusID = statusID;
            log.MetaDescription = metaDescription;
            log.MetaKeywords = metaKeywords;
            log.ActionedDate = DateTime.Now;
            log.ActionBy = Membership.GetUser().UserName;
            log.IpAdress = Globals.GetClientIPAddress();

            entity.AddToudv_Log(log);
            entity.SaveChanges();
        }
    }
}